import { configureStore, createSlice, combineReducers } from '@reduxjs/toolkit';
import { useMemo } from 'react';
import { useSelector, useDispatch, useStore as useReduxStore } from 'react-redux';

// 创建基础model函数，类似于mirror的model概念
const createModel = (initialState, reducers = {}, name = 'global') => {
  const slice = createSlice({
    name,
    initialState,
    reducers: {
      ...reducers,
      // 提供通用的setState方法，方便直接更新状态
      setState(state, action) {
        return { ...state, ...action.payload };
      }
    }
  });

  return {
    name: slice.name,
    reducer: slice.reducer,
    actions: slice.actions
  };
};

// 创建全局store
let store;

// 初始化store的函数
const initStore = (preloadedState = {}) => {
  // 默认models
  const defaultModels = {
    global: createModel(
      { 
        loading: false,
        error: null,
        user: null
      },
      {
        setLoading: (state, action) => {
          state.loading = action.payload;
        },
        setError: (state, action) => {
          state.error = action.payload;
        },
        setUser: (state, action) => {
          state.user = action.payload;
        }
      },
      'global'
    ),
    
    cart: createModel(
      {
        items: [],
        total: 0
      },
      {
        addItem: (state, action) => {
          const item = action.payload;
          const existingItem = state.items.find(i => i.id === item.id);
          if (existingItem) {
            existingItem.quantity += 1;
          } else {
            state.items.push({ ...item, quantity: 1 });
          }
          state.total = state.items.reduce((sum, item) => sum + (item.price * item.quantity), 0);
        },
        removeItem: (state, action) => {
          const id = action.payload;
          state.items = state.items.filter(item => item.id !== id);
          state.total = state.items.reduce((sum, item) => sum + (item.price * item.quantity), 0);
        },
        clearCart: (state) => {
          state.items = [];
          state.total = 0;
        }
      },
      'cart'
    )
  };

  // 合并reducers
  const rootReducer = combineReducers(
    Object.keys(defaultModels).reduce((acc, key) => {
      acc[key] = defaultModels[key].reducer;
      return acc;
    }, {})
  );

  return configureStore({
    reducer: rootReducer,
    preloadedState,
  });
};

// 获取或创建store实例
export const getStore = (preloadedState) => {
  let _store = store ?? initStore(preloadedState);

  // 在服务端渲染或hydration后，需要合并preloadedState
  if (preloadedState && store) {
    _store = initStore({
      ...store.getState(),
      ...preloadedState,
    });
    // 重置当前store
    store = _store;
  }

  // 创建store只需要一次，在客户端上
  if (!store) {
    store = _store;
  }

  return _store;
};

// 自定义hooks，简化状态管理使用
export const useModel = (modelName = 'global') => {
  const dispatch = useDispatch();
  const modelState = useSelector(state => state[modelName]);
  const reduxStore = useReduxStore();

  // 获取actions
  const actions = useMemo(() => {
    const model = reduxStore?.getState()?.[modelName];
    if (!model) return {};
    
    // 这里需要根据实际注册的model来获取actions
    return {};
  }, [modelName, reduxStore]);

  return {
    state: modelState,
    dispatch,
    actions
  };
};

// 创建和注册model的hook
export const useCreateModel = (modelConfig) => {
  const dispatch = useDispatch();
  
  return useMemo(() => {
    const { name, initialState, reducers } = modelConfig;
    const model = createModel(initialState, reducers, name);
    
    return {
      name: model.name,
      actions: model.actions,
      dispatch: (action) => dispatch(action)
    };
  }, [modelConfig, dispatch]);
};

// Provider组件包装器
export { Provider } from 'react-redux';